#include <iostream>
#include <string>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

void SetNonBlock(int fd)
{
    int f1 = fcntl(fd, F_GETFL);
    if(f1 < 0)
    {
        std::cerr << "获取文件标记位失败" << std::endl;
        return;
    }
    fcntl(fd, F_SETFL, f1 | O_NONBLOCK);
}

int main()
{
    char buffer[1024];
    SetNonBlock(0);
    while(true)
    {
        ssize_t s = read(0, buffer, sizeof(buffer) - 1);
        if(s > 0)
        {
            buffer[s] = 0;
            std::cout << "buffer: " << buffer << std::endl;
        }
        else 
        {
            if(errno == EAGAIN || errno == EWOULDBLOCK)
            {
                sleep(1);
                std::cout << "没有出错，仅仅是数据没有就绪" << std::endl;
                continue;
            }
            if(errno == EINTR)
            {
                std::cout << "读取被信号中断" << std::endl;
                continue;
            }
            std::cerr << "read error" << std::endl;
            break;
        }
    }
    return 0;
}

